<?php

namespace App\Providers\Services;

use App\Contracts\Services\Storage\StorageService;
use App\Support\Services\Storage\AliOSSService;
use Illuminate\Support\ServiceProvider;

class StorageServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;
    
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(StorageService::class, function ($app) {
            $config = $app['config']['storage.alioss'];
            if (empty($config)) {
                throw new \Exception('config alioss storage first');
            }

            $client = \Aliyun\OSS\OSSClient::factory([
                \Aliyun\OSS\Models\OSSOptions::ENDPOINT          => $config['server'],
                \Aliyun\OSS\Models\OSSOptions::ACCESS_KEY_ID     => $config['key'],
                \Aliyun\OSS\Models\OSSOptions::ACCESS_KEY_SECRET => $config['secret'],
            ]);

            return new AliOSSService($client, array_filter([
                'bucket'   => $config['bucket'],
                'schema'   => $config['schema'] ?: null,
                'base_url' => $config['base_url'] ?: '',
            ]));
        });
        $this->app->singleton(\App\App\Services\StorageService::class, function ($app) {
            return new \App\App\Services\StorageService($app[StorageService::class]);
        });
    }
    
    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            StorageService::class,
            \App\App\Services\StorageService::class,
        ];
    }
}
